<script setup lang="ts">
import DataTable from "./DataTable.vue";
import addDialogForm from "./components/addDialogForm.vue";

import { onMounted, ref } from "vue";
import { useRoute } from "vue-router";
import AddFill from "@iconify-icons/ri/add-circle-line";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { getRunningExperiments } from "@/api/LabExperimentApi";
import { listParentPlatform, deletePlatform } from "@/api/LabPlatformApi";
import type { PaginationProps } from "@pureadmin/table";
const { query } = useRoute();
const searchValue = ref("");
const platformId = ref("");

const platformName = ref("");

const labPlatformData = ref([]);
const configData = ref([]);

const dataLoading = ref(true);
const addFormDialogVisible = ref(false);

const pagination = ref<PaginationProps>({
  currentPage: 1,
  pageSize: 20,
  total: 0,
  align: "right",
  background: true,
  small: false,
  pageSizes: [10, 20, 100]
});

const getLabPlatformData = async () => {
  try {
    const Result = await listParentPlatform({ showParent: true });
    labPlatformData.value = Result.data;
    console.log(platformId.value, "platformId");
    if (!platformId.value) {
      const defaultConfigSelect = localStorage.getItem("defaultConfigSelect");
      if (defaultConfigSelect) {
        platformId.value = defaultConfigSelect;
      } else {
        labPlatformData.value.sort((a, b) => {
          const timeA = new Date(a.createTime);
          const timeB = new Date(b.createTime);

          return timeB - timeA;
        });
        platformId.value = labPlatformData.value[0].id;
      }

      //如果没有传入platformId，labPlatformData按时间排序，取第一个
    }
    platformName.value = labPlatformData.value.find(
      item => item.id === platformId.value
    ).name;
    // getLabExperimentDataByQuery(platformId.value as string, searchValue.value);
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const getConfigByQuery = async (expId: string, name: string) => {
  try {
    // const params = {
    //   expId: expId,
    //   name: name,
    //   ...pagination.value
    // };
    // if (params.expId) {
    //   delete params.name;
    // } else if (params.name) {
    //   delete params.expId;
    // } else {
    //   delete params.expId;
    //   delete params.name;
    // }
    const result = await listParentPlatform({
      curPage: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      parentExpId: platformId.value,
      showParent: true
    });
    configData.value = result.data;

    //通过parmas.name对configData的name进行模糊查找
    console.log(name);
    if (name) {
      configData.value = configData.value.filter(item => {
        if (item.name.indexOf(name) != -1) {
          return true;
        }
      });
    }

    pagination.value = {
      currentPage: 1,
      pageSize: pagination.value.pageSize,
      total: result.data ? result.total : 0
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};

const handleDeleteItem = expId => {
  ElMessageBox.confirm(`确定删除配置${expId}`, "提示", {
    type: "warning"
  })
    .then(async () => {
      const ret = await deletePlatform(expId);
      if (!ret.errorCode) {
        getConfigByQuery(platformId.value as string, searchValue.value);
        message(`删除成功`, { type: "success" });
      } else {
        message(`停止失败，${ret.message}`, { type: "error" });
      }
    })
    .catch(() => {});
};

const addNewConfig = () => {
  addFormDialogVisible.value = true;
};

const addConfigItem = () => {
  getConfigByQuery(platformId.value as string, searchValue.value);
};

const changeDefaultConfigSelect = () => {
  localStorage.setItem("defaultConfigSelect", String(platformId.value));
};
const disabled = ref(false);
onMounted(async () => {
  platformId.value = query.id ? String(query.id) : "";
  await getLabPlatformData();
  getConfigByQuery(platformId.value as string, searchValue.value);
  const res = await getRunningExperiments();
  if (!res.errorCode) {
    if (res.data) {
      disabled.value = true;
    }
    console.log(res);
  } else {
    message(`${res.message}`, { type: "error" });
  }
});
</script>

<template>
  <addDialogForm
    :platformName="platformName"
    :platformId="platformId"
    v-model:visible="addFormDialogVisible"
    @add-item="addConfigItem"
  />

  <div>
    <el-card class="box-card m-4" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="font-medium">实验配置</span>
        </div>
      </template>
      <div class="w-full flex justify-between mb-4">
        <el-row>
          <el-select
            clearable
            v-model="platformId"
            placeholder="选择实验平台"
            style="width: 200px; margin-right: 30px"
            @change="
              getConfigByQuery(platformId as string, searchValue);
              platformName = labPlatformData.find(
                item => item.id === platformId
              ).name;
              changeDefaultConfigSelect();
            "
          >
            <el-option
              v-for="item in labPlatformData"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <el-input
            style="width: 300px; margin-right: 12px"
            v-model="searchValue"
            placeholder="请输入实验配置名称"
            clearable
          >
            <template #suffix>
              <el-icon class="el-input__icon">
                <IconifyIconOffline
                  v-show="searchValue.length === 0"
                  :icon="Search"
                />
              </el-icon>
            </template>
          </el-input>
          <el-button
            @click="getConfigByQuery(platformId as string, searchValue)"
            type="primary"
            >查询
          </el-button>
        </el-row>

        <el-button
          :disabled="disabled"
          :icon="useRenderIcon(AddFill)"
          @click="addNewConfig()"
          >添加</el-button
        >
      </div>
      <DataTable
        :isRuning="disabled"
        :configData="configData"
        :labPlatformData="labPlatformData"
        :platformID="platformId"
        :newPagination="pagination"
        class="vue"
        @delete-item="handleDeleteItem"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.main-content {
  margin: 0 !important;
}
</style>
